package com.example.webcrawlercoursedesign;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

public class FragmentCCTV extends Fragment {
	private Context context;
	private List<News> newsList;//添加新闻
	private NewsAdapter adapter;//新闻适配器
	private Handler handler;
	private ListView listView;//展示新闻列表
	private NewsCache cache;

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		context = getActivity();
		//fragment的布局
		View fragmentView = inflater.inflate(R.layout.fragment_cctv, container, false);
		newsList = new ArrayList<>();//新闻列表
		listView = fragmentView.findViewById(android.R.id.list);
		cache = new NewsCache(context);
		getNews(context);//获取新闻
		/**
		 * 又开一个线程
		 *判断message
		 * 装上适配器
		 * 适配器版本的点击事件
		 */
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 1) {
					adapter = new NewsAdapter(context, newsList);//适配器
					listView.setAdapter(adapter);//设置适配器
					listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {//这一部分是点击之后转到新闻内容页面
							/**
							 * 获取位置,把数据装进news
							 * intent切换布局
							 * 传输数据
							 * 启动
							 */
							News news = newsList.get(position);//往定好数据框架的news里面传入数据
							Intent intent = new Intent(getActivity(), NewsDisplayActivity.class);//转到展示新闻的界面
							intent.putExtra("news_url", news.getNewsUrl());//把要打开的网址给他
							startActivity(intent);
						}
					});
				}
			}
		};
		return fragmentView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	private void getNews(final Context context) {

		new Thread(new Runnable() {
			@Override
			public void run() {
				if (!cache.isNetworkAvailable(context)){//无网络连接时加载库数据
					newsList = cache.loadCache(MySQLite.CCTV_NAME);
				}
				else {
					String cctv = "http://m.cctv.com/index.shtml";
					//手机央视网json数据在网页内
					try{
						Document doc = Jsoup.connect(cctv).get();
						Elements scripts = doc.getElementsByTag("script");
						String script = null;
						for (Element element : scripts){
							script = element.html();
							if (script.contains("var dataArrays= new Array();")) {
								break;
							}
						}//获取对应script标签下的数据
						String[] temp = script.split("var ");
						String jsonString = TextUtils.substring(temp[1], temp[1].indexOf(':') + 1, temp[1].lastIndexOf('}'));
						//提取json格式字符串
						Log.d("json",jsonString);
						JSONObject jsonObject = new JSONObject(jsonString);
						JSONArray jA = jsonObject.getJSONArray("data");
						//转换及解析，手机央视网格式->内容（标签）：标题（title）、url（url）、内容提要（brief1）、
						//时间和来源（time和textFrom）、题图（imgUrl1）
						for (int j = 0; j < 100; j++){
							JSONObject jO = (JSONObject)jA.get(j);
							String title = jO.get("title").toString();
							String url = jO.get("url").toString();
							String desc = jO.get("brief1").toString();
							String time = jO.get("time").toString() + " | " + jO.get("textFrom").toString();
							String imageUrl = jO.get("imgUrl1").toString();
							News news = new News(title, url, desc, time, imageUrl);
							newsList.add(news);
						}
						cache.updateCache(newsList, MySQLite.CCTV_NAME);//更新数据库
					}catch (Exception e){
						e.printStackTrace();
					}
				}
				Message msg = new Message();
				msg.what = 1;
				handler.sendMessage(msg);
			}
		}).start();
	}

}
